import { type Ref, ref, reactive, toRaw, onMounted, h } from "vue";
import editForm from "../form.vue";
import { usePublicHooks } from "@/views/hooks";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import type { carouselimageVO } from "./utils/types";
import dayjs from "dayjs";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  getBannerListPages,
  createBanner,
  updateBanner,
  deleteBanner
} from "@/api/banner";
import normalAvatar from "@/assets/normal-img.png";
import { getFullUrl } from "@/utils/auth";
export function useBanner(tableRef: Ref) {
  const { switchStyle } = usePublicHooks();
  const form = reactive({
    queryStartTime: "",
    queryEndTime: dayjs().format("YYYY-MM-DD 23:59:59"),
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "",
    isAsc: "asc",
    title: "",
    isActive: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const switchLoadMap = ref({});
  // 分页配置
  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 表格列配置
  const columns: TableColumnList = [
    { label: "轮播图名称", prop: "title" },
    {
      label: "轮播图",
      prop: "imageUrl",
      minWidth: 120,
      width: "120px",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.imageUrl ? getFullUrl(row.imageUrl) : normalAvatar}
          preview-src-list={Array.of(
            row.imageUrl ? getFullUrl(row.imageUrl) : normalAvatar
          )}
          class="w-[68px] h-[24px] rounded-[5px] align-middle"
        />
      )
    },
    { label: "链接地址", prop: "linkUrl" },
    { label: "排序码", prop: "displayOrder" },
    { label: "创建时间", prop: "createdAt" },
    {
      label: "有效",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isActive}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    // {
    //   label: "是否置顶",
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       v-model={scope.row.topup}
    //       active-value={1}
    //       inactive-value={0}
    //       active-text="是"
    //       inactive-text="否"
    //       inline-prompt
    //       style={switchStyle.value}
    //     />
    //   )
    // },
    // { label: "备注", prop: "Description" },
    {
      label: "操作",
      fixed: "right",
      width: "240px",
      slot: "operation" // 包含编辑、删除等操作
    }
  ];
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    form.pageSize = val;
    onSearch();
  }
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isActive ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.title
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        // 编辑banner
        await updateBanner(row);
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message("已成功修改", {
          type: "success"
        });
        await onSearch();
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
        onSearch();
      });
  }
  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    console.log(`handleSelectionChange: ${val}`);
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空banner的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onBatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (!curSelected.length) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }
    const Ids = curSelected.map(item => item.id);
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deleteDictTypeBatch(Ids).then(() => {
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
    message(`已删除banner编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
  }
  // 获取轮播图列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getBannerListPages(toRaw(form));
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.size;
    pagination.currentPage = data.current;
    setTimeout(() => (loading.value = false), 500);
  }
  // 新增/编辑轮播图
  function openDialog(type: string, row?: carouselimageVO) {
    const title = type === "add" ? "上传" : "编辑";
    addDialog({
      title: `${title}轮播图信息`,
      props: {
        formInline: {
          id: row?.id || "",
          imageUrl: row?.imageUrl || "",
          linkUrl: row?.linkUrl || "",
          title: row?.title || null,
          displayOrder: row?.displayOrder || "",
          isActive: row?.isActive || null
        }
      },
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as carouselimageVO;
        async function chores() {
          message(`您${title}了轮播图名称为${curData.noticename}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (type === "add") {
              await createBanner(curData);
              await chores();
            } else {
              // 编辑banner
              curData.id = row.id;
              await updateBanner(curData);
              await chores();
            }
          }
        });
      }
    });
  }
  // 删除轮播图
  function handleDelete(row) {
    // ElMessageBox.confirm(`确认删除轮播图【${row.title}】?`, "删除确认", {
    //   type: "warning"
    // }).then(() => {
    deleteBanner(row.id).then(() => {
      message(`删除轮播图 ${row.title} 成功`, { type: "success" });
      // 重置分页到第一页
      pagination.currentPage = 1;
      onSearch();
    });
    // });
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onBatchDel,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    onSelectionCancel,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
